package com.richard.room.operator.api.condition;

import com.richard.room.operator.api.statement.element.Condition;
import com.richard.room.operator.api.statement.element.Expression;
import com.richard.room.operator.api.type.ConditionRelation;

import java.util.ArrayList;

/**
 * @author: Richard
 * @createDate: 2023/8/7 18:11
 * @version: 1.0
 * @description: where 查询条件
 */
public class PropertyCondition {

    /**
     * 主where条件
     */
    private final Condition condition;

    /**
     * 当前操作的where条件
     */
    private Condition applyCondition;

    public PropertyCondition(Expression expression) {
        this.condition = Condition.newChildWhere();
        this.applyWhere(condition);
        this.getApplyWhere().add(expression);
    }

    /**
     * 获取where条件对象
     */
    public Condition getWhere() {
        return condition;
    }

    /**
     * 应用新的where对象
     */
    private void applyWhere(Condition condition) {
        this.applyCondition = condition;
    }

    /**
     * 获取设置好之后的applyWhere对象
     */
    private Condition getApplyWhere() {
        return applyCondition;
    }

    public PropertyCondition not(){
        Condition c = getApplyWhere();
        if(c.isLastCond() && c.conditionList != null && !c.conditionList.isEmpty()){
            c.conditionList.get(c.conditionList.size() - 1).isNot = true;
            return this;
        }
        if(c.expressions != null && !c.expressions.isEmpty()){
            c.expressions.get(c.expressions.size() -1).isNot = true;
            return this;
        }
        return this;
    }

    /**
     * 表达式左右条件反转，仅支持反转单个表达式。(例如：where a > 1,反转后是1 > a)
     */
    public PropertyCondition reverse(){
        Condition c = getApplyWhere();
        if(c.isLastCond()){
           return this;
        }
        if(c.expressions != null && !c.expressions.isEmpty()){
            c.expressions.get(c.expressions.size() -1).isReverse = true;
            return this;
        }
        return this;
    }

    /**
     * and 条件
     */
    public PropertyCondition and(PropertyCondition propertyCondition) {
        this.applyWhere(new Condition(ConditionRelation.and));
        this.getApplyWhere().addWhere(propertyCondition.condition);
        this.condition.addWhere(this.getApplyWhere());
        return this;
    }

    /**
     * or 条件
     */
    public PropertyCondition or(PropertyCondition propertyCondition) {
        this.applyWhere(new Condition(ConditionRelation.or));
        this.getApplyWhere().addWhere(propertyCondition.condition);
        this.condition.addWhere(this.getApplyWhere());
        return this;
    }
}
